package com.lplb.gateway.filter;

import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 *  跨域处理
 *
 * @author ws
 * @mail 1720696548@qq.com
 * @date 2020/2/13 0013 10:47
 */
@Component
@NoArgsConstructor
@Slf4j
@SuppressWarnings("all")
public class CrossOriginFilter implements GlobalFilter, Ordered {

    /**
     * 网关端口
     */
    @Value("${server.port}")
    private String serverPort;
    // 过滤执行顺序，负数可获取正常的url请求接口，大于等于0接口前服务名将被过滤
    @Override
    public int getOrder() {
        return 1;
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
        //保存端口号转发到具体的服务
        exchange.getResponse().getHeaders().add("serverPort", serverPort);
        return chain.filter(exchange);
    }
}



